package br.com.dataphonebr;

import java.util.List;

import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.preference.DialogPreference;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import br.com.dataphonebr.dao.impl.UsuarioDao;
import br.com.dataphonebr.entity.Usuario;
import br.com.dataphonebr.exception.CredentialsException;
import br.com.dataphonebr.service.CredentialsService;
import br.com.dataphonebr.util.Util;

public class UserCredentialsSettings extends  DialogPreference {
	

	public static final String USER_KEY_SETTINGS = "pref_nome_usuario";
	private EditText name;
	private EditText login;
	private EditText email;
	private TextView oldPasswordUserLbl;
	private TextView newPasswordUserLbl;
	private TextView repeatPasswordUserLbl;
	private EditText oldPassword;
	private EditText newPassword;
	private EditText repeatPassword;
	private CheckBox modifyPasswordCheckBox;
	private Usuario usuario = new Usuario();
	private String codigo;
	private Dialog dialog;
	private Button btSavePassword;
	private Button btCancelPassword;
	private Button btSave;
	private Button btCancel;
	private Util util = new Util();
	private UsuarioDao dao = new UsuarioDao(getContext());
	private UserSettingsActivity userSettingsActivity;

	public UserCredentialsSettings(Context context, AttributeSet attrs) {
		super(context, attrs);
		setDialogLayoutResource(R.layout.user_popup);
		setKey(USER_KEY_SETTINGS);
		setPositiveButtonText(null);
		setNegativeButtonText(null);
		userSettingsActivity = new UserSettingsActivity(Usuario.class);
	}
	
	@Override
	protected void onPrepareDialogBuilder(Builder builder) {
		builder.setTitle(R.string.userLabel);
		super.onPrepareDialogBuilder(builder);
	}
	
	@Override
	protected void onBindDialogView(View view) {
		name = (EditText)view.findViewById(R.id.usernamePopupTxt);
		name.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS);
		login = (EditText)view.findViewById(R.id.loginUserPopupTxt);
		email = (EditText)view.findViewById(R.id.emailUserPopupTxt);
		email.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
		modifyPasswordCheckBox = (CheckBox)view.findViewById(R.id.modifyPasswordCheckBox);
		if (userSettingsActivity.credentialsService.noUsers()){
			modifyPasswordCheckBox.setChecked(true);
			modifyPasswordCheckBox.setVisibility(View.INVISIBLE);
		} else {
			modifyPasswordCheckBox.setVisibility(View.VISIBLE);
		}
		btSave = (Button)view.findViewById(R.id.saveUserPopupBtn);
		btCancel = (Button)view.findViewById(R.id.cancelUserPopupBtn);
		btSave.setOnClickListener(resumeClick);
		btCancel.setOnClickListener(cancelClick);
		loadInstance();
		super.onBindDialogView(view);
	}
	
	OnClickListener savePasswordClick = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			if (persist())
				dialog.dismiss();
		}
	};
	
	OnClickListener resumeClick = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			prepare();
			String error = usuario.validate(false);
			if (!Util.isValidEmail(usuario.getEmail())){
				error = arg0.getContext().getString(R.string.msg_invalid_email);
			}
			if (error == null || error.isEmpty()){
				showPasswordDialog();
				getDialog().dismiss();
			} else {
				util.showToastMessageLong(error, getContext());
			}
		}
	};
	
	OnClickListener cancelClick = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			getDialog().dismiss();
		}
	};
	
	public boolean persist(){
		if (validate()){
			try {
				if (modifyPasswordCheckBox.isChecked() || userSettingsActivity.credentialsService.noUsers()){
					usuario.setPassword(newPassword.getText().toString().trim());
				}
				if (codigo == null || codigo.isEmpty()){
					dao.insert(usuario);
				}
				else {
					dao.update(usuario, usuario.getCodigo());
				}
				setSummary(usuario.getNome());
				persistString(usuario.getNome());
				util.showToastMessageLong(getContext().getString(R.string.msg_data_user_updated), getContext());
				return true;
			} catch (Exception e){
				util.showToastMessageLong(e.getMessage(), getContext());
				e.printStackTrace();
			}
		}
		return false;
	}
	
	private boolean validate(){
		try {
			if (userSettingsActivity.credentialsService.noUsers()){
				userSettingsActivity.credentialsService.checkNewUser(newPassword.getText().toString()
																	, repeatPassword.getText().toString()
																	, getContext());
			} else {
				if (modifyPasswordCheckBox.isChecked()){
					userSettingsActivity.credentialsService.checkUserFromNewPassword(usuario
																					, oldPassword.getText().toString()
																					, newPassword.getText().toString()
																					, repeatPassword.getText().toString()
																					, getContext());
				} else {
					userSettingsActivity.credentialsService.checkPasswordFromUserUpdate(usuario
																						, oldPassword.getText().toString()
																						, getContext());
				}
			}
		} catch (CredentialsException e) {
			util.showToastMessageLong(e.getMessage(), getContext());
			return false;
		}
		
		return true;
	}
	
	public void loadInstance(){
		usuario = new Usuario();
		List<Usuario> list = dao.selectAll();
		if (list != null && !list.isEmpty()){
			usuario = list.get(0);
		}
		if (usuario != null && usuario.getCodigo() != null){
			codigo = usuario.getCodigo().toString();
			name.setText(usuario.getNome());
			email.setText(usuario.getEmail());
			login.setText(usuario.getLogin());
			setSummary(usuario.getNome());
		} 
	}

	private void prepare(){
		if (codigo != null && !codigo.isEmpty())
			usuario.setCodigo(Long.parseLong(codigo));
		usuario.setNome(name.getText().toString());
		usuario.setEmail(email.getText().toString());
		usuario.setLogin(login.getText().toString());
		usuario.setEnabled(true);
	}
	
	private void showPasswordDialog(){
		dialog = new Dialog(getContext());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setCancelable(true);
		dialog.setContentView(R.layout.password_popup);

		oldPassword = (EditText)dialog.findViewById(R.id.oldPasswordUserTxt);
		newPassword = (EditText)dialog.findViewById(R.id.newPasswordUserTxt);
		repeatPassword = (EditText)dialog.findViewById(R.id.repeatPasswordUserTxt);
		oldPasswordUserLbl = (TextView) dialog.findViewById(R.id.oldPasswordUserLbl);
		newPasswordUserLbl = (TextView) dialog.findViewById(R.id.newPasswordUserLbl);
		repeatPasswordUserLbl = (TextView) dialog.findViewById(R.id.repeatPasswordUserLbl);
		if (userSettingsActivity.credentialsService.noUsers()){
			oldPasswordUserLbl.setVisibility(View.GONE);
			oldPassword.setVisibility(View.GONE);
			newPassword.setVisibility(View.VISIBLE);
			repeatPassword.setVisibility(View.VISIBLE);
			newPasswordUserLbl.setVisibility(View.VISIBLE);
			repeatPasswordUserLbl.setVisibility(View.VISIBLE);
		} else {
			if (modifyPasswordCheckBox.isChecked()){
				oldPasswordUserLbl.setVisibility(View.VISIBLE);
				oldPassword.setVisibility(View.VISIBLE);
				newPassword.setVisibility(View.VISIBLE);
				repeatPassword.setVisibility(View.VISIBLE);
				newPasswordUserLbl.setVisibility(View.VISIBLE);
				repeatPasswordUserLbl.setVisibility(View.VISIBLE);
				oldPasswordUserLbl.setText(R.string.oldPasswordLabel);
			} else {
				newPassword.setVisibility(View.GONE);
				repeatPassword.setVisibility(View.GONE);
				newPasswordUserLbl.setVisibility(View.GONE);
				repeatPasswordUserLbl.setVisibility(View.GONE);
				oldPasswordUserLbl.setText(R.string.passwordLabel);
			}
		}
		btSavePassword = (Button) dialog.findViewById(R.id.savePasswordPopupBtn);
		btSavePassword.setOnClickListener(savePasswordClick);
		btCancelPassword = (Button) dialog.findViewById(R.id.cancelPasswordPopupBtn);
		OnClickListener cancelPasswordClick = new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				dialog.dismiss();
			}
		};
		btCancelPassword.setOnClickListener(cancelPasswordClick);
		dialog.show();
	}
	
	public class UserSettingsActivity extends GenericActivity<Usuario>{
		
		private CredentialsService credentialsService;

		public UserSettingsActivity(Class<Usuario> clazz) {
			super(clazz);
			credentialsService = new CredentialsService(this);
		}
	}

}
